<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>函数</title>
</head>
<body>
    <h1>函数</h1>

    <script>
        // 箭头函数
        // bad
        const foo = function(x) {
            return x + 1;
        };

        // good
        const foo = (x) => x + 1;

        // 参数解构
        // bad
        function getFullName(user) {
            const firstName = user.firstName;
            const lastName = user.lastName;
            return `${firstName} ${lastName}`;
        }

        // good
        function getFullName({ firstName, lastName }) {
            return `${firstName} ${lastName}`;
        }

        // 默认参数
        // bad
        function handleRequest(url, method) {
            method = method || 'GET';
            // ...
        }

        // good
        function handleRequest(url, method = 'GET') {
            // ...
        }

        // 实际应用示例
        // 异步函数
        const fetchData = async (url) => {
            try {
                const response = await fetch(url);
                return await response.json();
            } catch (error) {
                console.error('Error:', error);
                throw error;
            }
        };

        // 高阶函数
        const withLogging = (fn) => async (...args) => {
            console.log('调用函数:', fn.name);
            try {
                const result = await fn(...args);
                console.log('函数返回:', result);
                return result;
            } catch (error) {
                console.error('函数错误:', error);
                throw error;
            }
        };

        // 函数组合
        const compose = (...fns) => (x) => 
            fns.reduceRight((y, f) => f(y), x);

        // 柯里化
        const curry = (fn) => {
            const arity = fn.length;
            return function curried(...args) {
                if (args.length >= arity) {
                    return fn(...args);
                }
                return (...moreArgs) => curried(...args, ...moreArgs);
            };
        };
    </script>
</body>
</html> 